<template>
  <div class="login">
    <!-- 顶部导航开始 -->
    <mt-header title="优机汇手机商城" class="header">
      <router-link to="/" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
    </mt-header>
    <!-- 顶部导航结束 -->
    <!-- 面板开始 -->
    <mt-field
      type="text"
      lable="用户名"
      placeholder="请输入用户名"
      v-model="uname"
      @blur.native.capture="unameBlur"
      :state="unameState"
    ></mt-field>
    <mt-field
      type="password"
      lable="密码"
      placeholder="请输入密码"
      v-model="upwd"
    ></mt-field>
    <mt-button type="primary" size="large" @click="login" class="btn-login"
      >登录</mt-button
    >
    <!-- 面板结束 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      uname: "",
      upwd: "",
      unameState: "",
    };
  },
  methods: {
    unameBlur() {
      let unameReg = /^[0-9a-zA-Z_]{6,12}$/;
      if (unameReg.test(this.uname)) {
        this.unameState = "success";
        return true;
      } else {
        this.unameState = "error";
        this.$toast({
          message: "用户名不合法，请输入6~12位大写字母/小写字母/数字/下划线",
          position: "middle",
          duration: 3000,
        });
        return false;
      }
    },
    login() {
      if (this.unameBlur()) {
        this.axios
          .post("/login", "uname=" + this.uname + "&upwd=" + this.upwd)
          .then(res => {
            if (res.data.code == 0) {
              this.$messagebox("登录信息", "登录失败!");
            } else {
              localStorage.setItem("uname", this.uname);
              this.$router.push("/");
            }
          });
      }
    },
  },
};
</script>

<style scoped>
.login {
  margin-top: 45px;
}
.header {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
}
.btn-login {
  margin-top: 30px;
}
</style>
